import os
import socket,random,json,threading,queue,sys
import time

from header import *
from multiprocessing import Process,Queue

def handle_ack(acked, s, currentAck):
    print("in thread")
    while 1:
        data, addr = s.recvfrom(1024)
        tempPk = Packet()
        tempPk.decode(data)
        if tempPk.ackNo == currentAck+1:
            acked.put(1)
            print("put")
            break

def rdt_send(serverAddress, port, bitStream, sock, currentAck):
    acked = Queue()
    send_count = 0
    listener_thread = threading.Thread(target=handle_ack, args = (acked, sock, currentAck,))
    listener_thread.start()
    while acked.empty():
        sock.sendto(bitStream, (serverAddress, port))
        time.sleep(1)
        send_count = send_count + 1
        if send_count == 5:
            print("connect fail")
            break

def rdt_send_for_server(serverAddress, bitStream, sock, currentAck):
    acked = Queue()
    send_count = 0
    listener_thread = threading.Thread(target=handle_ack, args = (acked, sock, currentAck,))
    listener_thread.start()
    while acked.empty():
        sock.sendto(bitStream, serverAddress)
        time.sleep(1)
        send_count = send_count + 1
        if send_count == 5:
            print("connect fail")
            break

"""
def rdt_send(sock, addr, port, pk, currentAck):
    acked = Queue()
    send_count = 0
    thread = threading.Thread(target = command_ack, args=(sock, acked, currentAck,))
    thread.start()
    target = (addr, port)
    sock.sendto(pk, (addr, port))

    while acked.empty():
        sock.sendto(pk, (addr, port))
        send_count = send_count + 1
        if send_count == 5:
            print("connect fail")
            return False
    return  True
"""
